package cn.sfa.controller.login;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.sfa.common.utils.CommonUtil;
import cn.sfa.common.utils.FormValidate;
import cn.sfa.common.utils.MajorKeyGenerate;
import cn.sfa.entity.users.SaleUserLoginLog;
import cn.sfa.entity.users.SaleUsersLogin;
import cn.sfa.service.login.LoginService;
import cn.sfa.service.manage.NewsService;
import cn.sfa.service.role.RoleService;

/**
 * 
* 类名称：LoginController   
* 类描述： 用户登录处理类
* 创建人：lenovo   
* 创建时间：2012-2-14 下午10:26:32   
* 修改人：lenovo   
* 修改时间：2012-2-14 下午10:26:32   
* 修改备注：    
* @version v1.0
 */
@Controller
@RequestMapping("/login/index")
public class LoginController{
	Logger log  = LoggerFactory.getLogger(LoginController.class);
	
	private String msg;

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	@Autowired
	LoginService loginService;
	@Autowired
	NewsService newsService;
	@Autowired
	MajorKeyGenerate keyGenerate;
	
	@Autowired
	RoleService roleService;
	@RequestMapping
	public String login(ModelMap model,HttpServletRequest request) throws Exception{

		String username = request.getParameter("username");
		String pwd = request.getParameter("pwd");

			

		if(CommonUtil.isEmpty(username) || CommonUtil.isEmpty(pwd)){//如果用户名或密码都为空
			model.put("msg", "用户名或密码不能为空");
			return "index";
		}
		SaleUsersLogin saleUser=loginService.getUserByLoginName(username);
		
		
		SaleUsersLogin user=loginService.getUserByLoginName(username);
		if(!loginService.getUser(username, pwd))
		{
			model.put("msg", "用户名或密码错误");
			return "index";
		}
		
		//判断是否是第一次登录，如果是，则修改密码才能进系统,如果是内勤则不需要登录修改密码
//		List users=loginService.getUser(username);
//		if(users.size()==0 
//				&& !"USERTYPE_3".equals(user.getUserType()) && !"USERTYPE_4".equals(user.getUserType()) )
//		{
//			request.getSession().setAttribute("loginname", username);
//			return "/setMail";
//		}
		
		SaleUserLoginLog saleLog=new SaleUserLoginLog();

		//把AD里User的信息取出来放入SaleUsersLoginLog中，然后存入登录日记信息表
		//saleLog.setCreateUid(user.getCreateUid());
		saleLog.setCreateDate(new Date());
		//saleLog.setUpdateId(user.getUpdateId());
		saleLog.setUpdateDate(new Date());
		saleLog.setLoginName(user.getLoginName()); 
		saleLog.setUserAgentId(user.getUserAgentId());
		saleLog.setSaleUsersLoginId(user.getSaleUsersLoginId());
		//存入登录日记表
		loginService.addUserLoginLog(saleLog, request);
//		SaleUsersLogin user=new SaleUsersLogin();
//		user.setUserName("admin");
		
		user.setUserPassword(pwd);
		List roleList=roleService.getRoles(user.getSaleUsersLoginId());
		//给代理人和助理初始化角色
		if("USERTYPE_1".equals(user.getUserType())||"USERTYPE_2".equals(user.getUserType())){
			Map map = new HashMap();
			map.put("roleId","LER0000000000046");
			roleList.add(map);
		}
		user.setUserRoles(roleList);
		request.getSession().setAttribute("user", user);
	
		
		if(user.getUserType().equals("USERTYPE_1"))
		{
			request.getSession().setAttribute("agentid", user.getSaleUsersLoginId());
		}else if(user.getUserType().equals("USERTYPE_2"))
		{
			String agentid=user.getUserAgentId();
			request.getSession().setAttribute("agentid", agentid);
		}
		
		if(user.getUserType().equals("USERTYPE_3"))
		{
			request.getSession().setAttribute("adminid", user.getSaleUsersLoginId());
		}else if(user.getUserType().equals("USERTYPE_4"))
		{
			String adminid=user.getCreateUid();
			user.setUserPassword(pwd);
			loginService.updatePassword(pwd, "", pwd);
			request.getSession().setAttribute("adminid", adminid);
		}
		log.info("用户"+username+"登录成功!"); 
		return "redirect:/news/index";
	}
	@RequestMapping("sendValidateCode")
	public String sendValidateCode(HttpServletRequest request,ModelMap map)
	{
		String loginname=(String)request.getSession().getAttribute("loginname");
		SaleUsersLogin user=loginService.getUserByLoginName(loginname);
		String mail=request.getParameter("email");
		

		return "/setMail";
	}
	@RequestMapping("loginUpdatePwd")
	public String loginUpdatePwd(HttpServletRequest request,ModelMap map)
	{
		String randCode=(String)request.getSession().getAttribute("randCode");
		String randCodeRequest=request.getParameter("randCode");
		String email=request.getParameter("email");
		map.put("email", email);
		if(randCode!=null && randCode.equals(randCodeRequest))
		{
			return "/toUpdatePwd";
		}
		 
		map.put("msg", "验证码不正确");
		return "/sendRandCode";
	}
	
	@RequestMapping("toUpdatePwd")
	public String toUpdatePwd(HttpServletRequest request,ModelMap map)
	{
		String loginname=(String)request.getSession().getAttribute("loginname");
		String userpassword=request.getParameter("userPassword");
		String newPassword=request.getParameter("newpassword");
		String newPassword2=request.getParameter("newpassword2");
		String email=request.getParameter("email");
		map.put("email", email);
		map.put("userPassword", userpassword);//用于回显数据
		map.put("newpassword", newPassword);//用于回显数据
		map.put("newpassword2", newPassword2);//用于回显数据
		//表单验证
		if(userpassword==null || "".equals(userpassword))
		{
			map.put("userpassword", "密码不能为空！");
			return "toUpdatePwd";
		}else if(newPassword==null || "".equals(newPassword))
		{
			map.put("newPassword", "新密码不能为空！");
			return "toUpdatePwd";
		}else if(newPassword2==null || "".equals(newPassword2))
		{
			map.put("newPassword2", "确认密码不能为空！");
			return "toUpdatePwd";
		}
		else if(newPassword.length()<7 || newPassword.length()>14)
		{
			map.put("newPassword", "新密码长度必须在7到14位");
			return "toUpdatePwd";
		}else if(!FormValidate.pwdStreng(newPassword))
		{
			map.put("newPassword", "新密码必须包含字母，数字，特殊字符");
			return "toUpdatePwd";
		}else if(newPassword2.length()<7 || newPassword2.length()>14)
		{
			map.put("newPassword2", "确认密码长度必须在7到14位");
			return "toUpdatePwd";
		}else if(!newPassword.equals(newPassword2))
		{
			map.put("newPassword2", "两次输入的密码不一致！");
			return "toUpdatePwd";
		}
		
		//在ＡＤ里进行认证看是否存在
		SaleUsersLogin saleUser=loginService.getUserByLoginName(loginname);
		
		String userStatus=saleUser.getUserStatus();
		
		if(userStatus!=null && userStatus.equals("n"))
		{
			map.put("msg", "你的帐号已被禁用!");
			return "alter";
		}
			map.put("userpassword", "密码错误！");
		
		return "toUpdatePwd";
	}
	
	@RequestMapping("logout")
	public String logout(HttpServletRequest request,ModelMap map)
	{
		request.getSession().removeAttribute("user");
		request.getSession().invalidate();
		return "index";
	}
	
}
